cmake_minimum_required(VERSION 3.21)

function(set_board BOARD_ID)
  include(updatedb)
  updatedb() # updates board_db if needed
  include(boards_db)

  set(KEYWORDS SERIAL USB XUSB VIRTIO BOOTLOADER)
  cmake_parse_arguments(PARSE_ARGV 1 BOARD "" "${KEYWORDS}" "")

  if(DEFINED BOARD_UNPARSED_ARGUMENTS OR DEFINED BOARD_KEYWORDS_MISSING_VALUES)
    message(SEND_ERROR "Invalid call to set_board(); some arguments went unparsed")
  endif()

  if(DEFINED BOARD_BOOTLOADER)
    set(BOARD_ID "${BOARD_ID}_${BOARD_BOOTLOADER}")
  endif()

  if (NOT TARGET ${BOARD_ID})
    message(SEND_ERROR "Board ${BOARD_ID} not found. Maybe the board database is not up-to-date?")
    return()
  endif()
  add_library(board ALIAS ${BOARD_ID})
  set(BUILD_VARIANT_PATH ${${BOARD_ID}_VARIANT_PATH} PARENT_SCOPE)
  set(BOARD_MAXSIZE ${${BOARD_ID}_MAXSIZE} PARENT_SCOPE)
  set(BOARD_MAXDATASIZE ${${BOARD_ID}_MAXDATASIZE} PARENT_SCOPE)
  set(MCU ${${BOARD_ID}_MCU} PARENT_SCOPE)
  set(FPCONF ${${BOARD_ID}_FPCONF} PARENT_SCOPE)

  # if the user passed in an invalid value, then the target won't be found
  # and cmake will output an error message
  if(DEFINED BOARD_SERIAL)
    if (TARGET ${BOARD_ID}_serial_${BOARD_SERIAL})
      target_link_libraries(${BOARD_ID} INTERFACE ${BOARD_ID}_serial_${BOARD_SERIAL})
    else()
      message(SEND_ERROR "SERIAL=${BOARD_SERIAL} not supported (at least for this board)")
    endif()
  elseif(TARGET ${BOARD_ID}_serial_generic)
    target_link_libraries(${BOARD_ID} INTERFACE ${BOARD_ID}_serial_generic)
  endif()

  if(DEFINED BOARD_USB)
    if (TARGET ${BOARD_ID}_usb_${BOARD_USB})
      target_link_libraries(${BOARD_ID} INTERFACE ${BOARD_ID}_usb_${BOARD_USB})
    else()
      message(SEND_ERROR "USB=${BOARD_USB} not supported (at least for this board)")
    endif()
  elseif(TARGET ${BOARD_ID}_usb_none)
    target_link_libraries(${BOARD_ID} INTERFACE ${BOARD_ID}_usb_none)
  endif()

  if(DEFINED BOARD_XUSB)
    if (TARGET ${BOARD_ID}_xusb_${BOARD_XUSB})
      target_link_libraries(${BOARD_ID} INTERFACE ${BOARD_ID}_xusb_${BOARD_XUSB})
    else()
      message(SEND_ERROR "XUSB=${BOARD_XUSB} not supported (at least for this board)")
    endif()
  elseif(TARGET ${BOARD_ID}_xusb_FS)
    target_link_libraries(${BOARD_ID} INTERFACE ${BOARD_ID}_xusb_FS)
  endif()

  if(DEFINED BOARD_VIRTIO)
    if (TARGET ${BOARD_ID}_virtio_${BOARD_VIRTIO})
      target_link_libraries(${BOARD_ID} INTERFACE ${BOARD_ID}_virtio_${BOARD_VIRTIO})
    else()
      message(SEND_ERROR "VIRTIO=${BOARD_VIRTIO} not supported (at least for this board)")
    endif()
  elseif(TARGET ${BOARD_ID}_virtio_disable)
    target_link_libraries(${BOARD_ID} INTERFACE ${BOARD_ID}_virtio_disable)
  endif()
endfunction()
